/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package csci6450.chickenFriedFS.metaServer.threads;

import csci6450.chickenFriedFS.nuggetCore.Nugget;
import csci6450.chickenFriedFS.nuggetCore.NuggetConstants;
import csci6450.chickenFriedFS.nuggetCore.ThreadStatus;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 *
 * @author jacobschoen
 */
public class RemoveNuggetFromServer extends Thread{

    private Nugget nugget;
    private ThreadStatus status;

    public RemoveNuggetFromServer(Nugget nugget, ThreadStatus status){
        this.nugget = nugget;
        this.status = status;
    }

    @Override
    public void run() {
        Socket socket = null;
        try {
            //connect to the appropriate nugget server
            socket = new Socket(nugget.getNuggetLocation(), nugget.getNuggetServerPort());
            // open I/O streams for objects
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            outputStream.writeObject(NuggetConstants.RM);
            outputStream.flush();
            //the port to get the file on
            Integer port = (Integer) inputStream.readObject();
            socket.close();

            //now get the nugget

            //connect to the appropriate nugget server
            socket = new Socket(nugget.getNuggetLocation(), port);
            // open I/O streams for objects
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            //the port to get the file on
            outputStream.writeObject(this.nugget);
            
            inputStream = new ObjectInputStream(socket.getInputStream());
            String temp = (String)inputStream.readObject();
            socket.close();
            boolean success = temp.equals(NuggetConstants.SUCCESS );
            this.status.setSuccessful(success);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            this.status.setSuccessful(false);
        } catch (IOException iOException) {
            iOException.printStackTrace();
            this.status.setSuccessful(false);
        } catch (Exception e){
            e.printStackTrace();
            this.status.setSuccessful(false);
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            this.status.setFinished(true);
        }
    }

}
